package com.gzq.singleton.exam07;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

public class MethodLocked implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public static void main(String[] args) throws NoSuchMethodException,
			SecurityException, InstantiationException, IllegalAccessException,
			IllegalArgumentException, InvocationTargetException, IOException,
			ClassNotFoundException {
		MethodLocked singleton1 = MethodLocked.getSingleton();
		MethodLocked singleton2 = MethodLocked.getSingleton();
		System.out.println(singleton1);
		System.out.println(singleton2);

		Constructor<MethodLocked> declaredConstructor = MethodLocked.class
				.getDeclaredConstructor();
		MethodLocked innStaticCst = declaredConstructor.newInstance();
		System.out.println(innStaticCst);

		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		ObjectOutputStream oos = new ObjectOutputStream(baos);
		oos.writeObject(singleton1);
		byte[] byteArray = baos.toByteArray();

		ByteArrayInputStream bais = new ByteArrayInputStream(byteArray);
		ObjectInputStream ois = new ObjectInputStream(bais);
		MethodLocked readObject = (MethodLocked) ois.readObject();
		System.out.println(readObject);

	}

	private static MethodLocked singleton;

	private MethodLocked() {
	}

	public static synchronized MethodLocked getSingleton() {
		if (singleton == null) {
			singleton = new MethodLocked();
		}
		return singleton;
	}

}
